import { Form, Breadcrumb, Card, Input, Radio, Select, Upload, Button, Space, message } from "antd"
import { useEffect, useRef, useState } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { observer } from 'mobx-react-lite'
import { PlusOutlined } from '@ant-design/icons'
import { useStore } from '@/store'
import ReactQuill from 'react-quill';
import { http } from '@/uitls'
import 'react-quill/dist/quill.snow.css';
import './index.scss'
const { Option } = Select



const Publish = () => {
    const { channelStore } = useStore([])
    console.log("channelStore", channelStore)
    const [fileList, setFileList] = useState([])

    //使用useRef声明一个仓库
    const cacheImgList = useRef()
    const uploadChange = ({ fileList }) => {
        console.log(fileList)
        //存放图片
        const farmatList = fileList.map(file=>{
            // 上传完毕
            if(file.response){
                return {
                    url:file.response.data.url
                }
            }
            //否则不做处理
            return file
        })
        setFileList(farmatList)
        //上传成功的时候同时把图片列表存入仓库一份
        cacheImgList.current = farmatList
    }

    //切换图片
    const [imgCount, setImageCount] = useState(1)
    const radioChange = (e) => {
        console.log(e)
        const len = e.target.value
        setImageCount(len)
        if (cacheImgList.current.length === 0) {
            return false
        }
        //从仓库里面取对应的图片数量 交给我们用来渲染图片列表的fileList
        if (len === 1) {//如果是单图取数组中的第一项
            const img = cacheImgList.current ? cacheImgList.current[0] : []
            setFileList([img])
        } else if (len === 3) {//如果是三图把所有的图片拿到存到fileList
            setFileList(cacheImgList.current)
        }
    }
   

    //编辑功能 文案适配 路由参数id 判断条件
    const [params] = useSearchParams()
    const id = params.get('id')
    console.log("router", id)
    //拿到form实例对象
    const form = useRef()
    //数据回显 根据id调接口
    useEffect(() => {
        const loadDetail = async () => {
            const res = await http.get(`/mp/articles/${id}`)
            console.log("res", res)
            const data = res.data
            form.current.setFieldsValue({ ...data, type: data.cover.type })
            //调用setFildList方法回显 upload
            const formatImgList = res.data.cover.images.map(url => ({ url }))
            setFileList(formatImgList)
            //回显切换图片暂存列表也存一份 fileList回显列表和数据结构保持一致
            cacheImgList.current = formatImgList
        }
        if (id) {
            console.log("form.current", form.current)
            loadDetail()
        }
    }, [id])

     //提交表单
     const navigate = useNavigate()
     const onFinish = async (values) => {
         console.log(values)
         //数据的二次处理 cover字段
         const { channel_id, content, title, type } = values
         const params = {
             channel_id,
             content,
             title,
             type,
             cover: {
                 type: 1,
                 images: fileList.map(item => item.url)
             }
         }
         console.log(params)
         if (id) {//更新
             await http.put(`/mp/articles/${id}?draft=false`, params)
         } else {//新增接口
             await http.post('/mp/articles?draft=false', params)
         }
         navigate('/article')
         message.success(`${id ? "更新成功" : "发布成功"}`)
     }

    return (
        <diV>
            <Card
                title={
                    <Breadcrumb separator=">">
                        <Breadcrumb.Item>
                            <Link>首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            {id ? "编辑" : "发布"}文章
                        </Breadcrumb.Item>
                    </Breadcrumb>
                }
            >
                <Form
                    lableCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ type: 1, content: "内容区域" }}
                    onFinish={onFinish}
                    ref={form}
                >
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[{ required: true, message: "必填" }]}
                    >
                        <Input placeholder="请输入" style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item
                        label="频道"
                        name="channel_id"
                        rules={[{ required: true, message: "必填" }]}
                    >
                        <Select placeholder="请选择" style={{ width: 400 }}>
                            {channelStore.channelList.map((item) => (
                                <Option key={item.id} value={item.id} >{item.name}</Option>
                            ))}

                        </Select>
                    </Form.Item>
                    <Form.Item label="封面">
                        <Form.Item
                            name="type"
                        >
                            <Radio.Group onChange={radioChange}>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                                <Radio value={0}>无图</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {imgCount > 0 && (
                            <Upload
                                name="image"
                                listType="picture-card"
                                className="avatr-uploader"
                                showUploadList
                                fileList={fileList}
                                onChange={uploadChange}
                                action="http://geek.itheima.net/v1_0/upload"
                                multiple={imgCount > 1}
                                maxCount={imgCount}
                            >
                                <div style={{ marginTop: 8 }}>
                                    <PlusOutlined />
                                </div>
                            </Upload>
                        )
                        }
                    </Form.Item>
                    <Form.Item
                        lable="内容"
                        name="content"
                        rules={[{ required: true, message: "必填" }]}
                    >
                        {/* value={value} onChange={setValue} */}
                        <ReactQuill
                            defaultValue={1}
                            theme="snow"
                        />
                    </Form.Item>
                    <Form.Item
                        wrapperCol={{ offset: 4 }}
                    >
                        <Space>
                            <Button
                                size="large"
                                type="primary"
                                htmlType="submit"
                            >
                                {id ? "更新" : "发布"}文章
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </diV>
    )
}

export default observer(Publish) 